package org.apache.database.helper;

import org.apache.database.dao.Condition;
import org.apache.database.enums.SelectActionEnum;
import org.apache.database.excpt.ConfigError;
import org.apache.database.result.ResultHandler;
import org.apache.database.utils.AnnotationUtil;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class QueryHelper extends BaseHelper {

    private ResultHandler resultHandler = new ResultHandler();

    /**
     * 查找全部，可分页
     *
     * @param tClass
     * @param offset
     * @param size
     * @param <T>
     * @return
     */
    public <T> List<T> findAll(Class<T> tClass, int offset, int size) {
        String tableName = getTabName(tClass);
        if (tableName == null) {
            throw new ConfigError(tClass + "类上为标记表注解(TabName)");
        }
        List<String> fieldsNames = AnnotationUtil.getFieldsNames(tClass);
        String sql = SelectActionEnum.SELECT.init().asField(fieldsNames).findAll(tableName, offset, size);
        ResultSet resultSet = getSqlExecute().executeForResult(sql);
        try {
            return resultHandler.forList(tClass, resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return Collections.EMPTY_LIST;
    }

    public <T> T findOneById(Class<T> tClass, Serializable value) {
        String primaryKey = AnnotationUtil.getPrimaryKey(tClass);
        Condition condition = new Condition.Builder()
                .whereEq(primaryKey, value).builder();

        List<T> result = findWithCondition(tClass, condition);
        if (result != null && result.size() >= 1) {
            return result.get(0);
        }
        return null;
    }

    public <T> List<T> findWithCondition(Class<T> tClass, Condition c) {
        List<String> fieldsNames = AnnotationUtil.getFieldsNames(tClass);
        String sql = SelectActionEnum.SELECT.init().asField(fieldsNames).findWithCondition(getTabName(tClass), c);
        ResultSet resultSet = (ResultSet) getSqlExecute().executeForResult(sql);
        try {
            return resultHandler.forList(tClass, resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return Collections.EMPTY_LIST;
    }


    public int getCount(Class<?> tClass) {
        String tabName = getTabName(tClass);
        ResultSet resultSet = (ResultSet) getSqlExecute().executeForResult(SelectActionEnum.SELECT.init().getCount(tabName));
        return resultHandler.forType(int.class, resultSet);
    }
}
